<template>
  <div class="import-extra-data">
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" tab="无平台数据列表">
        <div class="table-area">
          <div class="table-toolbar">
            <a-button type="primary" :loading="exporting" @click="handleExport">
              <a-icon type="download" />导出Excel
            </a-button>
            <a-button type="primary" :loading="loading" style="margin-left: 8px" @click="getTableData">
              <a-icon type="reload" />刷新
            </a-button>
          </div>
          <vxe-table
            ref="xTable"
            :loading="loading"
            :data="tableData"
            :auto-resize="true"
            :height="listTableHeight"
            resizable
            show-overflow="tooltip"
          >
            <vxe-column field="contribution_id" width="60" title="id" />
            <vxe-column field="title" title="作品名" />
            <vxe-column field="author1_name" title="作者1">
              <template v-slot="{ row }">
                {{ row.author1_name }}
              </template>
            </vxe-column>
            <vxe-column field="author2_name" title="作者2">
              <template v-slot="{ row }">
                <template v-if="row.author2_name">
                  {{ row.author2_name }}
                </template>
              </template>
            </vxe-column>
            <vxe-column field="author3_name" title="作者3">
              <template v-slot="{ row }">
                <template v-if="row.author3_name">
                  {{ row.author3_name }}
                </template>
              </template>
            </vxe-column>
            <vxe-column field="project_group_name" title="项目组" />
            <vxe-column field="score" title="总分" />
            <vxe-column field="submission_date" title="提交时间">
              <template v-slot="{ row }">
                {{ formatDate(row.submission_date) }}
              </template>
            </vxe-column>
            <vxe-column field="tiktok_likes" title="抖音点赞数">
              <template v-slot="{ row }">
                {{ row.tiktok_likes || '-' }}
              </template>
            </vxe-column>
            <vxe-column field="channels_views" title="视频号播放量">
              <template v-slot="{ row }">
                {{ row.channels_views || '-' }}
              </template>
            </vxe-column>
            <vxe-column field="channels_likes" title="视频号点赞数">
              <template v-slot="{ row }">
                {{ row.channels_likes || '-' }}
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="平台数据导入">
        <div class="table-area">
          <div class="table-toolbar">
            <a-upload
              accept=".xlsx,.xls"
              :before-upload="handleBeforeUpload"
              :show-upload-list="false"
              :disabled="importLoading || executing"
            >
              <a-button type="primary" style="margin-right: 8px" :loading="importLoading">
                <a-icon type="upload" />导入数据
              </a-button>
            </a-upload>
            <a-button 
              type="primary" 
              :disabled="!importData.length || importLoading"
              :loading="executing"
              @click="handleExecute"
            >
              <a-icon type="play-circle" />执行
            </a-button>
          </div>
          <vxe-table
            ref="importTable"
            :loading="importLoading || executing"
            :data="importData"
            :auto-resize="true"
            :height="importTableHeight"
            resizable
            show-overflow="tooltip"
          >
            <vxe-column field="contribution_id" width="60" title="ID" />
            <vxe-column field="title" title="作品名" />
            <vxe-column field="author1_name" title="作者1" />
            <vxe-column field="author2_name" title="作者2" />
            <vxe-column field="author3_name" title="作者3" />
            <vxe-column field="tiktok_likes" title="抖音点赞数" />
            <vxe-column field="channels_views" title="视频号播放量" />
            <vxe-column field="channels_likes" title="视频号点赞数" />
            <vxe-column field="status" title="执行情况" width="200">
              <template v-slot="{ row }">
                <template v-if="row.status">
                  <a-tag :color="getStatusColor(row.status)">
                    {{ getStatusText(row.status) }}
                    <template v-if="row.message">
                      : {{ row.message }}
                    </template>
                  </a-tag>
                </template>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
  import {
    apiContributionGetPendingDataList,
    apiContributionImportPlatformData
  } from '@/api/featch'
  import moment from 'moment'
  import XLSX from 'xlsx'

  export default {
    name: 'ImportExtraData',
    data() {
      return {
        // 表格数据
        tableData: [],
        loading: false,
        listTableHeight: null,
        importTableHeight: null,
        
        // 导入相关
        importData: [],
        importLoading: false,
        executing: false,
        exporting: false
      }
    },
    mounted() {
      this.initTableHeight()
      // this.getTableData()

      // 监听窗口大小变化
      window.addEventListener('resize', this.initTableHeight)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.initTableHeight)
    },
    methods: {
      /**
       * @description 初始化表格高度
       */
      initTableHeight() {
        const clientHeight = document.documentElement.clientHeight
        // 列表表格高度：页面高度 - 头部高度(64px) - main容器margin(24px * 2) - main容器padding(24px * 2) - tabs高度(44px) - 导出按钮区域(56px)
        this.listTableHeight = clientHeight - 64 - 48 - 48 - 44 - 56

        // 导入表格高度：页面高度 - 头部高度(64px) - main容器margin(24px * 2) - main容器padding(24px * 2) - tabs高度(44px) - 导入按钮区域(56px)
        this.importTableHeight = clientHeight - 64 - 48 - 48 - 44 - 56
      },

      /**
       * @description 获取表格数据
       */
      async getTableData() {
        this.loading = true
        try {
          const res = await apiContributionGetPendingDataList()
          if (res.code === 200) {
            this.tableData = res.data || []
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.loading = false
      },

      /**
       * @description 格式化日期
       */
      formatDate(date) {
        if (!date) return ''
        return moment(date).format('YYYY-MM-DD HH:mm:ss')
      },

      /**
       * @description 处理导出Excel
       */
      async handleExport() {
        if (!this.tableData.length) {
          this.$message.warning('暂无数据可导出')
          return
        }

        this.exporting = true
        try {
          // 准备导出数据
          const exportData = this.tableData.map(item => ({
            'ID': item.contribution_id,
            '标题': item.title,
            '作者1': item.author1_name,
            '作者2': item.author2_name || '',
            '作者3': item.author3_name || '',
            '项目组': item.project_group_name,
            '总分': item.score,
            '提交日期': this.formatDate(item.submission_date),
            '抖音点赞数': item.tiktok_likes || '-',
            '视频号播放量': item.channels_views || '-',
            '视频号点赞数': item.channels_likes || '-'
          }))

          // 创建工作簿
          const ws = XLSX.utils.json_to_sheet(exportData)
          const wb = XLSX.utils.book_new()
          XLSX.utils.book_append_sheet(wb, ws, '无平台数据列表')

          // 导出文件
          XLSX.writeFile(wb, `无平台数据列表_${moment().format('YYYY-MM-DD')}.xlsx`)
          this.$message.success('导出成功')
        } catch (err) {
          this.$message.error('导出失败')
          console.error(err)
        } finally {
          this.exporting = false
        }
      },

      /**
       * @description 执行导入
       */
      async handleExecute() {
        if (!this.importData.length) {
          this.$message.warning('请先导入数据')
          return
        }

        this.executing = true
        try {
          // 遍历导入数据
          const updatedData = [...this.importData]
          for (let i = 0; i < updatedData.length; i++) {
            const item = updatedData[i]
            // 只检查ID是否存在
            if (!item.contribution_id) {
              updatedData[i] = {
                ...item,
                status: 'error',
                message: 'ID不能为空'
              }
              continue
            }

            try {
              // 处理数值，非法值转为0
              const tiktok_likes = parseInt(item.tiktok_likes) || 0
              const channels_views = parseInt(item.channels_views) || 0
              const channels_likes = parseInt(item.channels_likes) || 0

              const res = await apiContributionImportPlatformData({
                contribution_id: item.contribution_id,
                tiktok_likes,
                channels_views,
                channels_likes
              })
              
              if (res.code === 200) {
                updatedData[i] = {
                  ...item,
                  status: 'success',
                  message: '导入成功'
                }
              } else {
                updatedData[i] = {
                  ...item,
                  status: 'error',
                  message: res.message
                }
              }
            } catch (err) {
              updatedData[i] = {
                ...item,
                status: 'error',
                message: err.message || '导入失败'
              }
            }
          }

          // 更新表格数据
          this.importData = updatedData

          // 刷新无平台数据列表
          this.getTableData()
          
          // 统计结果
          const successCount = updatedData.filter(item => item.status === 'success').length
          const totalCount = updatedData.length
          this.$message.info(`导入完成：成功${successCount}条，失败${totalCount - successCount}条`)
        } catch (err) {
          this.$message.error('导入过程出错')
        } finally {
          this.executing = false
        }
      },

      /**
       * @description 获取状态文字
       */
      getStatusText(status) {
        const statusMap = {
          'success': '导入成功',
          'error': '导入失败'
        }
        return statusMap[status] || '未知状态'
      },

      /**
       * @description 获取状态颜色
       */
      getStatusColor(status) {
        const colorMap = {
          'success': 'green',
          'error': 'red'
        }
        return colorMap[status] || 'default'
      },

      /**
       * @description 上传前处理
       */
      handleBeforeUpload(file) {
        this.importLoading = true
        const reader = new FileReader()
        reader.onload = (e) => {
          try {
            const data = new Uint8Array(e.target.result)
            const workbook = XLSX.read(data, { type: 'array' })
            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]
            const results = XLSX.utils.sheet_to_json(worksheet)
            
            // 转换数据格式
            this.importData = results.map(item => ({
              contribution_id: item['ID'],
              title: item['作品名'],
              author1_name: item['作者1'],
              author2_name: item['作者2'],
              author3_name: item['作者3'],
              tiktok_likes: item['抖音点赞数'],
              channels_views: item['视频号播放量'],
              channels_likes: item['视频号点赞数']
            }))
            
            this.$message.success('数据导入成功')
          } catch (err) {
            this.$message.error('文件解析失败')
            console.error(err)
          }
          this.importLoading = false
        }
        reader.readAsArrayBuffer(file)
        return false
      }
    }
  }
</script>

<style lang="less" scoped>
  .import-extra-data {
    height: 100%;

    .table-area {
      background: #fff;
      border-radius: 4px;

      .table-toolbar {
        padding: 16px 24px;
        text-align: right;
      }
    }
  }
</style>